package com.icexxx.icemock.mock;

import java.util.Calendar;
import java.util.Date;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;

public class IdcardMock implements IceMock {

	@Override
	public String mock(Integer minVal, Integer maxVal, Integer minWidth, Integer maxWidth, String enums,
			String key) {
		if (minVal == null) {
			minVal = 1980;
		}
		if (maxVal == null) {
			maxVal = 2010;
		}
		return gen(minVal, maxVal);
	}

	/**
	 * 模拟身份证号码
	 * 
	 * @return
	 */
	public static String gen(Integer minVal, Integer maxVal) {
		Integer[] data = { 11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 50, 51,
				52, 53, 54, 61, 62, 63, 64, 65, 71, 81, 82 };
		int randomInt1 = RandomUtil.randomInt(1000, 9999);
		int year = RandomUtil.randomInt(minVal, maxVal);
		int day = RandomUtil.randomInt(365);
		String randomNumbers = RandomUtil.randomNumbers(3);
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, 1, 1);
		Date date = calendar.getTime();
		Date offsetDay = DateUtil.offsetDay(date, day);
		String province = String.valueOf(RandomUtil.randomEle(data));
		String city = String.valueOf(randomInt1);
		StringBuilder sb = new StringBuilder();
		sb.append(province);
		sb.append(city);
		String format = "yyyyMMdd";
		String dateStr = DateUtil.format(offsetDay, format);
		sb.append(dateStr);
		sb.append(randomNumbers);
		String checkCode = checkCode(sb.toString());
		sb.append(checkCode);
		return sb.toString();
	}

	private static String checkCode(String string) {
		int[] coefficient = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3 };
		int sum = 0;
		for (int i = 0; i < string.length(); i++) {
			char ch = string.charAt(i);
			sum += (ch - 48) * coefficient[i % 10];
		}
		sum = sum % 11;
		int remainder = (12 - sum) % 11;
		if (remainder == 10) {
			return "X";
		} else {
			return String.valueOf(remainder);
		}
	}
}
